﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Reactive.Linq;
using System.Windows;
using Wulong.Phone.Dianping.Models;
using Wulong.Phone.Dianping.Services;

namespace Wulong.Phone.Dianping.Views
{
    public partial class SearchView
    {
        public SearchView()
        {
            InitializeComponent();
            _suggestions = new ObservableCollection<SearchSuggestion>();
            Search.ItemsSource = _suggestions;
            Search.ValueMemberPath = "Name";
            var observerCollectionChanged = Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
                d=>d.Invoke,
                h => _suggestions.CollectionChanged += h, 
                h => _suggestions.CollectionChanged -= h);
            var observerTextChanged = Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
                d => d.Invoke,
                h => Search.TextChanged += h,
                h => Search.TextChanged -= h);
            observerTextChanged
                .DistinctUntilChanged()
                .Throttle(TimeSpan.FromSeconds(2))
                .ObserveOnDispatcher()
                .Subscribe(x => LoadSuggestions());
            observerCollectionChanged
                .ObserveOnDispatcher()
                .Subscribe(x => Search.PopulateComplete());
        }

        private ObservableCollection<SearchSuggestion> _suggestions;
        public IEnumerable<SearchSuggestion> Suggestions
        {
            get { return _suggestions; }
        }
        public void LoadSuggestions()
        {
            _suggestions.Clear();
            DianpingService.ObservableSuggestion(
                Search.Text, ((City)Cities.SelectedItem).Code, ((Channel)Channels.SelectedItem).Id)
                .Where(item=>!string.IsNullOrWhiteSpace(item.Name))
                .ObserveOnDispatcher()
                .Subscribe(item => _suggestions.Add(item));
        }
    }
}